package shmallarchitect.faces.util;

import java.util.LinkedList;
import java.util.List;
import javax.faces.model.SelectItem;
import shmallarchitect.jpa.entities.Gallery;
import shmallarchitect.jpa.entities.Owner;
import shmallarchitect.jpa.entities.User;
import shmallarchitect.jpa.jsf.GalleryController;

/**
 *
 * @author jaccus
 */
public class GalleryUtil {

    public static String addNewGallery(Gallery newGallery) {
        if (!galleryAlreadyExists(newGallery.getName())) {

            try {
                Owner owner = newGallery.getOwner();
                final long ownerId = OwnerUtil.getOwnerIdByName(owner.getName());
                if(ownerId == -1) {
                    OwnerUtil.addNew(owner);
                    owner.setId(OwnerUtil.getOwnerIdByName(owner.getName()));
                } else {
                    owner.setId(ownerId);
                }

                GalleryController uc = new GalleryController();
                Gallery gallery = uc.getGallery();
                copyProperties(newGallery, gallery);
                uc.create();
                return gallery.getName();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static List<Gallery> getGalleriesForUser(String login) {
        GalleryController gc = new GalleryController();
        List<Gallery> galleryItems = gc.getGalleryItems();

        List<Gallery> galleriesForUser = new LinkedList<Gallery>();

        for (Gallery gallery : galleryItems) {
            if (gallery.getUser().getLogin().equals(login)) {
                galleriesForUser.add(gallery);
            }
        }
        return galleriesForUser;
    }

    private static void copyProperties(Gallery newGallery, Gallery gallery) {
        gallery.setName(newGallery.getName());
        gallery.setCity(newGallery.getCity());
        gallery.setCountry(newGallery.getCountry());
        gallery.setNumber(newGallery.getNumber());
        gallery.setStreet(newGallery.getStreet());
        gallery.setZip(newGallery.getZip());
        gallery.setId(newGallery.getId());
        User user = new User();
        UserUtil.copyUserProperties(newGallery.getUser(), user);
        gallery.setUser(user);

        Owner owner = new Owner();
        OwnerUtil.copyProperties(newGallery.getOwner(), owner);
        gallery.setOwner(owner);

    }

    private static boolean galleryAlreadyExists(String name) {
        GalleryController gc = new GalleryController();
        SelectItem[] items = gc.getGalleryItemsAvailableSelectMany();
        for (int i = 0; i < items.length; i++) {
            Gallery gallery = (Gallery) items[i].getValue();
            if (gallery.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }
}
